<?php
/**
 * Tools.php
 *
 * @author: cnx7 <zysafe@live.cn> 2019-07-27
 */

namespace common\domain\helper;

class Tools
{
    /**
     * 判断当前服务器系统
     * @return string
     */
    public static function getOS()
    {
        if (PATH_SEPARATOR == ':') {
            return 'Linux';
        } else {
            return 'Windows';
        }
    }

    /**
     * 生成时间格式： yyyymmddHHmmss
     * @return false|string
     */
    public static function tradeDate()
    {
        return date('YmdHis', time());
    }

    /**
     * 当前微秒数
     * @return number
     */
    public static function getMicroTime()
    {
        list ($uSec, $sec) = explode(" ", microtime());
        return (( float )$uSec + ( float )$sec);
    }

    /**
     * 返回32位MD5值
     * @param $str
     * @return string
     */
    public static function md5($str)
    {
        if (empty($str)) return '';
        return md5($str);
    }

    /**
     * 获取客户端IP
     * @return string
     */
    public static function getClientIp()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $res = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
        return $res;
    }

    /**
     * 获取IP所在地址
     * @param string $ip
     * @return string
     */
    public static function getIpLocation($ip = '')
    {
        if ($ip === '') $ip = self::getClientIp();


        $ret = \Yii::$app->cache->get('location:ip:' . $ip);

        if (!$ret) {
            $req = 'http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip;
            $res = HttpCurl::request($req, 'get');
            $res = json_decode($res, true);

            if ($res['data']['isp'] == '内网IP') {
                $ret = '内网IP';
            } else {
                $ret = $res['data']['country'] . $res['data']['region'] . $res['data']['city'] . $res['data']['isp'];
            }

            \Yii::$app->cache->set('location:ip:' . $ip, $ret, 600);
        }

        return $ret;
    }

    public static function getISP()
    {
        $ip = self::getClientIp();

        $ret = \Yii::$app->cache->get('location:isp:' . $ip);

        if (!$ret) {
            $req = 'http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip;

            $res = HttpCurl::request($req, 'get');
            $res = json_decode($res, true);

            $ret = $res['data']['isp'];

            \Yii::$app->cache->set('location:isp:' . $ip, $ret, 600);

        }
        return $ret;
    }

    /**
     * 生成随机字符串
     * @param int $len
     * @return string
     */
    public static function genRandomString($len)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars); // 将数组打乱
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars [mt_rand(0, $charsLen)];
        }
        return $output;
    }

    /**
     * 随机数光数字
     * @param int $len
     * @return string
     */
    public static function genRandomNum($len)
    {
        $chars = array(
            "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars); // 将数组打乱
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars [mt_rand(0, $charsLen)];
        }
        return $output;
    }

    // 邮件发送
    public static function sendEmail($email, $title = "测试", $msg = "测试")
    {
        $mail = \Yii::$app->mailer->compose();
        $mail->setTo($email);
        $mail->setSubject($title);
        $mail->setTextBody($msg);   //发布纯文字文本
        return $mail->send();
    }

    // 生成token
    public static function setToken($len = 32)
    {
        return \Yii::$app->getSecurity()->generateRandomString($len);
    }

    //按范围生成小数
    public static function randFloat($min = 0, $max = 1)
    {
        return $min + mt_rand() / mt_getrandmax() * ($max - $min);
    }

    /**
     * 计算时间差
     * @param int $timestamp1 时间戳开始
     * @param int $timestamp2 时间戳结束
     * @return array
     */
    public static function timeDiff($timestamp1, $timestamp2): array
    {
        if ($timestamp2 <= $timestamp1) {
            return ['hours' => 0, 'minutes' => 0, 'seconds' => 0];
        }
        $timediff = $timestamp2 - $timestamp1;
        // 时
        $remain = $timediff % 86400;
        $hours = intval($remain / 3600);

        // 分
        $remain = $timediff % 3600;
        $mins = intval($remain / 60);
        // 秒
        $secs = $remain % 60;

        return ['hours' => $hours, 'minutes' => $mins, 'seconds' => $secs];
    }

    /**
     * 下划线转驼峰
     * @param $uncamelized_words
     * @param string $separator
     * @return string
     */
    public static function camelize($uncamelized_words, $separator = '_')
    {
        $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
        return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
    }

    /**
     * 驼峰命名转下划线命名
     * @param $camelCaps
     * @param string $separator
     * @return string
     */
    function uncamelize($camelCaps, $separator = '_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }

}
